package Web;

import java.io.IOException;
import java.net.*;

/**
 * @author wuhan
 * @date 2019/10/16 15:32
 * Udp send
 * 1.建立udp socket服务
 * 2.提供数据，并将数据封装到数据包中
 * 3.通过socket 服务的发送功能，将数据包发出去
 * 4.关闭资源
 */
public class SocketDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket=new DatagramSocket();
        byte[] buf = "Udp ge men lai lai".getBytes();

        DatagramPacket datagramPacket =
                new DatagramPacket(buf,buf.length, InetAddress.getByName("192.168.210.1"),10000);

        datagramSocket.send(datagramPacket);
        datagramSocket.close();

    }
}

class UdpReceiver{
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(10000);

        while (true){
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf,buf.length);

            ds.receive(dp);

            InetAddress address = dp.getAddress();

//        byte[] data = dp.getData();
            String data =new String(dp.getData(),0,dp.getLength());
            int port = dp.getPort();

            System.out.println(address.toString()+" "+ data +" "+port);
        }


//        ds.close();

    }
}
